package com.bootdo.common.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.JsonObject;
import org.apache.commons.codec.digest.Md5Crypt;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.util.ByteSource;

import java.security.MessageDigest;
import java.util.*;

public class MD5Utils {
	private static final String SALT = "1qazxsw2";

	private static final String ALGORITH_NAME = "md5";

	private static final int HASH_ITERATIONS = 2;

	public static String encrypt(String pswd) {
		String newPassword = new SimpleHash(ALGORITH_NAME, pswd, ByteSource.Util.bytes(SALT), HASH_ITERATIONS).toHex();
		return newPassword;
	}

	public static String encrypt(String username, String pswd) {
		String newPassword = new SimpleHash(ALGORITH_NAME, pswd, ByteSource.Util.bytes(username + SALT),
				HASH_ITERATIONS).toHex();
		return newPassword;
	}
	public static String createDySigin(Map jsonObject) throws Exception {
        Set set = jsonObject.keySet();
        Set set1 = setSort(set, "des");
        /*agent_id：100034
        secret：88b57fddb473aad644ef4b807678a16a*/
        String f = "agent_id100034";
        for(Object o:set1){
            if(o.equals("agent_id") || o.equals("signid")){
                continue;
            }
            Object o1 = jsonObject.get(o);
            f +=o+String.valueOf(o1);
        }
        f +="88b57fddb473aad644ef4b807678a16a";
        String md5 = getMD5(f);
        return md5;

    }

    public static String getMD5(String str) throws Exception {
        /** 创建MD5加密对象 */
        MessageDigest md5 = MessageDigest.getInstance("MD5");
        /** 进行加密 */
        md5.update(str.getBytes());
        /** 获取加密后的字节数组 */
        byte[] md5Bytes = md5.digest();
        String res = "";
        for (int i = 0; i < md5Bytes.length; i++){
            int temp = md5Bytes[i] & 0xFF;
            if (temp <= 0XF){ // 转化成十六进制不够两位，前面加零
                res += "0";
            }
            res += Integer.toHexString(temp);
        }
        return res;
    }

    public static Set<String>  setSort(Set<String>  set,String orderby){
        Set<String> newSet=new HashSet<>();
        if(orderby.equals("")||orderby.equals("des")){//顺序
            newSet = new TreeSet<String>();
            for(String str:set){
                if(str.equals("signid")){
                    continue;
                }
                newSet.add(str);
            }
        }

        if(orderby.equals("")||orderby.equals("desc")){//倒叙
            newSet = new TreeSet<String>(new Comparator<String>() {
                @Override
                public int compare(String o1, String o2) {
                    return o1.compareTo(o2);
                }
            });
        }

        return newSet;

    }
}
